package vip.xiaonuo.biz.modular.tempinfo.service.impl;


import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.tempinfo.entity.SysDynamicTable;
import vip.xiaonuo.biz.modular.tempinfo.entity.SysTempFields;

import javax.annotation.RegEx;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysDynamicTableServiceImpl {

    public String createTableSql(String tableName,String tableComment, List<SysTempFields> fields) {

        fields = firstAdd(fields);
        fields = endAppend(fields);

        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE IF NOT EXISTS `" + tableName + "` (");

        for (SysTempFields field : fields) {
            sb.append("`"+field.getModel() + "` " + getTypeName(field.getDataType()) + "'" + field.getName() + "',");
        }

        sb.append("PRIMARY KEY (`id`))  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='" + tableComment + "';");
        String sql = sb.toString();
        return sql;
    }

    public List<SysTempFields> firstAdd(List<SysTempFields> fields) {

        //发起人，执行人，接收人
        SysTempFields sysTempFields = new SysTempFields();
        sysTempFields.setDataType("id");
        sysTempFields.setModel("id");
        sysTempFields.setName("id");

        fields.add(0,sysTempFields);
        return fields;
    }

    public List<SysTempFields> endAppend(List<SysTempFields> fields) {


        SysTempFields fieldCreate = new SysTempFields();
        fieldCreate.setDataType("datetime");
        fieldCreate.setModel("create_time");
        fieldCreate.setName("创建时间");

        SysTempFields fieldUpdate = new SysTempFields();
        fieldUpdate.setDataType("datetime");
        fieldUpdate.setModel("update_time");
        fieldUpdate.setName("修改时间");


        SysTempFields fieldDelete = new SysTempFields();
        fieldDelete.setDataType("datetime");
        fieldDelete.setModel("delete_time");
        fieldDelete.setName("删除时间");
        fields.add(fieldCreate);
        fields.add(fieldUpdate);
        fields.add(fieldDelete);
        return fields;
    }


    private String getTypeName(String fieldType) {
        if (fieldType.contains("int")) {
            return " int(11) DEFAULT 0 COMMENT ";
        } else if (fieldType.contains("textlong")) {
            return " longtext COMMENT ";
        }  else if (fieldType.contains("id")) {
            return " varchar(20) not null COMMENT ";
        }  else if (fieldType.contains("varchar")) {
            return " varchar(255) DEFAULT NULL COMMENT ";
        }else if (fieldType.contains("datetime")) {
            return " datetime DEFAULT NULL COMMENT ";
        } else {
            return " text COMMENT ";
        }
    }
//
//    // 省略其他方法
//
//    public SysDynamicTable saveData(String tableName, SysDynamicTable data) {
//        String sql = "INSERT INTO " + tableName + " (" + StringUtils.join(data.getValues().keySet(), ",") + ") VALUES (" + StringUtils.repeat("?", ",", data.getValues().size()) + ")";
//        Query query = entityManager.createNativeQuery(sql);
//        int index = 1;
//        for (Object value : data.getValues().values()) {
//            query.setParameter(index++, value);
//        }
//        query.executeUpdate();
//        Long id = ((BigInteger)entityManager.createNativeQuery("SELECT LAST_INSERT_ID()").getSingleResult()).longValue();
//        data.setId(id);
//        return data;
//    }
//
//    public void deleteData(String tableName, Long id) {
//        String sql = "DELETE FROM " + tableName + " WHERE id = ?";
//        Query query = entityManager.createNativeQuery(sql);
//        query.setParameter(1, id);
//        query.executeUpdate();
//    }
//
//
//
//    public SysDynamicTable updateData(String tableName, SysDynamicTable data) {
//        String sql = "UPDATE " + tableName + " SET " + StringUtils.join(data.getValues().keySet().stream().map(k -> k + " = ?").collect(Collectors.toList()), ",") + " WHERE id = ?";
//        Query query = entityManager.createNativeQuery(sql);
//        int index = 1;
//        for (Object value : data.getValues().values()) {
//            query.setParameter(index++, value);
//        }
//        query.setParameter(index, data.getId());
//        query.executeUpdate();
//        return data;
//    }
//
//    public SysDynamicTable findById(String tableName, Long id) {
//        String sql = "SELECT * FROM " + tableName + " WHERE id = ?";
//        Query query = entityManager.createNativeQuery(sql);
//        query.setParameter(1, id);
//        List<Object[]> results = query.getResultList();
//        if (results.isEmpty()) {
//            return null;
//        } else {
//            Object[] result = results.get(0);
//            SysDynamicTable data = new SysDynamicTable();
//            data.setId((Long)result[0]);
////            for (int i = 1; i < result.length; i++) {
////                data.getValues().put(getColumnName(tableName, i), result[i]);
////            }
////
//            return null;
//        }
//    }
//
//    public List<SysDynamicTable> findAll(String tableName) {
//        String sql = "SELECT * FROM " + tableName;
//        Query query = entityManager.createNativeQuery(sql);
//        List results = query.getResultList();
//        return results;
//    }
}
